@file:Suppress("UNCHECKED_CAST")

package com.example.smart.base.utils

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.example.smart.base.dialog.base.BaseDialog
import com.example.smart.base.ui.activity.BaseActivity
import com.example.smart.base.ui.fragment.BaseFragment
import java.lang.reflect.ParameterizedType

fun <V : ViewBinding> BaseActivity<*>.getViewBinding(view: View): V {
    try {
        val typeArguments = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments
        if (typeArguments.isNullOrEmpty().not()) {
            val clazz = (typeArguments.first() as Class<V>).toString()
            if (clazz.isEmpty().not() && clazz.length > 6) {
                val method = Class.forName(clazz.substring(6, clazz.length)).getMethod("bind", View::class.java)
                return method.invoke(null, view) as V
            }
        }
    } catch (_: Exception) {
    }
    throw IllegalArgumentException("ViewBinding初始化失败，请检查配置")
}

fun <V : ViewBinding> BaseFragment<*>.getViewBinding(inflater: LayoutInflater, container: ViewGroup?): V {
    try {
        val typeArguments = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments
        if (typeArguments.isNullOrEmpty().not()) {
            val clazz = (typeArguments.first() as Class<V>).toString()
            if (clazz.isEmpty().not() && clazz.length > 6) {
                val method = Class.forName(clazz.substring(6, clazz.length))
                    .getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
                return method.invoke(null, inflater, container, false) as V
            }
        }
    } catch (ignore: Exception) {
        ignore.printStackTrace()
    }
    throw IllegalArgumentException("ViewBinding初始化失败，请检查配置")
}

fun <V : ViewBinding> BaseDialog<*>.getViewBinding(view: View): V {
    try {
        val typeArguments = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments
        if (typeArguments.isNullOrEmpty().not()) {
            val clazz = (typeArguments.first() as Class<V>).toString()
            if (clazz.isEmpty().not() && clazz.length > 6) {
                val method = Class.forName(clazz.substring(6, clazz.length)).getMethod("bind", View::class.java)
                return method.invoke(null, view) as V
            }
        }
    } catch (_: Exception) {
    }
    throw IllegalArgumentException("ViewBinding初始化失败，请检查配置")
}